﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

using System.Reflection;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Collections;

namespace Light.Utility
{
    /// <summary>
    /// 反射辅助类
    /// </summary>
    public class ReflectionHelper
    {
        /// <summary>
        /// 获取属性的Descriptoin特性标签值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetPropertyDescription<T>(string propertyName)
        {
            return GetPropertyAttribute<T, DescriptionAttribute>(propertyName, "Description");
        }

        /// <summary>
        /// 获取属性的DisplayName特性标签值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetPropertyDisplayName<T>(string propertyName)
        {
            return GetPropertyAttribute<T, DescriptionAttribute>(propertyName, "DisplayName");
        }

        public static string GetDisplayName(MemberInfo memberInfo, string defaultDisplayName)
        {
            if (memberInfo != null)
            {
                object[] customAttributes = memberInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true);
                if ((customAttributes != null) && (customAttributes.Length > 0))
                {
                    return ((DisplayNameAttribute)customAttributes[0]).DisplayName;
                }
                if (defaultDisplayName != null)
                {
                    return defaultDisplayName;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取枚举类型的描述特性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetEnumDescription<T>(T obj)
        {
            string desc = string.Empty;

            Type type = typeof(DescriptionAttribute);
            FieldInfo[] infos = typeof(T).GetFields();

            foreach (FieldInfo fi in infos)
            {
                if (fi.Name == obj.ToString())
                {
                    object[] arr = fi.GetCustomAttributes(type, true);
                    if (arr.Length > 0)
                    {
                        desc = ((DescriptionAttribute)arr[0]).Description;
                    }
                    break;
                }
            }

            return desc;
        }


        public static Dictionary<string, object> GetEnumDescriptions<T>()
        {

            Array array = Enum.GetValues(typeof(T));


            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (T item in array)
            {
                dic.Add(GetEnumDescription<T>(item), item as int?);
            }


            //Type type = typeof(DescriptionAttribute);

            //foreach (FieldInfo fi in typeof(T).GetFields())
            //{
            //    object[] arr = fi.GetCustomAttributes(type, true);
            //    if (arr.Length > 0)
            //    {
            //        nvc.Add(((DescriptionAttribute)arr[0]).Description, fi.GetValue(fi));
            //    }
            //}

            return dic;

        }


        /// <summary>
        /// 获取属性的特性标签值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="propertyName">属性名称</param>
        /// <param name="attributeName">标签名称</param>
        /// <returns></returns>
        public static string GetPropertyAttribute<T, TAtrribute>(string propertyName, string attributeName)
        {
            string attrValue = string.Empty;
            PropertyInfo pi = typeof(T).GetProperty(propertyName);

            if (pi == null)
            {
                throw new TypeLoadException("类型:" + typeof(T).ToString() + " 不存在属性" + propertyName);
            }
            attrValue = GetAttributeValue<TAtrribute>(pi, attributeName);
            return attrValue;
        }


        public static Dictionary<string, string> GetImportFields<T>(bool export)
        {
            return GetImportFields(typeof(T), export, false);
        }

        /// <summary>
        /// 获取指定类型的导入导出列
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="export">是否为导出操作</param>
        /// <param name="sub">是否包含自定义属性的属性</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetImportFields(Type type, bool export, bool sub)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo p in properties)
            {
                Type pType = p.PropertyType;
                object[] attrs = p.GetCustomAttributes(typeof(ImportFieldAttribute), true);
                bool importable = attrs != null && attrs.Length > 0;
                bool isRelated = false;

                if (!importable)
                {
                    continue;
                }
                else
                {
                    isRelated = ((ImportFieldAttribute)attrs[0]).IsRelatived;
                }

                if (export && sub && !isRelated)//如果是导出，并且标记了不关联，则跳过此属性
                {
                    continue;
                }


                //自定义类属性
                if (!pType.Module.Name.Contains("mscorlib") && !pType.IsEnum)
                {
                    Dictionary<string, string> dicInner = GetImportFields(pType, export, true);
                    foreach (var key in dicInner.Keys)
                    {
                        string innerProperyName = p.Name + "." + key;
                        dic.Add(innerProperyName, dicInner[key]);
                    }

                }//泛型集合属性
                else if (pType is IList && pType.IsGenericType)
                {
                    Type genericType = pType.GetGenericArguments()[0];
                    Dictionary<string, string> dicInner = GetImportFields(genericType, export, true);
                    foreach (var key in dicInner.Keys)
                    {
                        string innerProperyName = p.Name + "[0]." + key;
                        dic.Add(innerProperyName, dicInner[key]);
                    }
                }//系统类型属性
                else
                {
                    dic.Add(p.Name, ((ImportFieldAttribute)attrs[0]).Name);
                }
            }
            return dic;
        }

        /// <summary>
        /// 获取导出的列排序值(取原始设置值，无序)
        /// </summary>
        /// <param name="type">实体类型</param>
        /// <param name="sub">是否为属性类型</param>
        /// <returns></returns>
        public static Dictionary<string, KeyValuePair<string, int>> GetImportOrdinal(Type type, bool sub)
        {
            Dictionary<string, KeyValuePair<string, int>> dic = new Dictionary<string, KeyValuePair<string, int>>();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo p in properties)
            {
                Type pType = p.PropertyType;
                object[] attrs = p.GetCustomAttributes(typeof(ImportFieldAttribute), true);
                bool importable = attrs != null && attrs.Length > 0;
                bool isRelated = false;

                if (!importable)
                {
                    continue;
                }
                else
                {
                    isRelated = ((ImportFieldAttribute)attrs[0]).IsRelatived;
                }

                if (sub && !isRelated)//如果是导出，并且标记了不关联，则跳过此属性
                {
                    continue;
                }


                //自定义类属性
                if (!pType.Module.Name.Contains("mscorlib") && !pType.IsEnum)
                {
                    Dictionary<string, KeyValuePair<string, int>> dicInner = GetImportOrdinal(pType, true);
                    foreach (var key in dicInner.Keys)
                    {
                        string innerProperyName = p.Name + "." + key;
                        dic.Add(innerProperyName, dicInner[key]);
                    }

                }//泛型集合属性
                else if (pType is IList && pType.IsGenericType)
                {
                    Type genericType = pType.GetGenericArguments()[0];
                    Dictionary<string, KeyValuePair<string, int>> dicInner = GetImportOrdinal(genericType, true);
                    foreach (var key in dicInner.Keys)
                    {
                        string innerProperyName = p.Name + "[0]." + key;
                        dic.Add(innerProperyName, dicInner[key]);
                    }
                }//系统类型属性
                else
                {
                    ImportFieldAttribute attr = (ImportFieldAttribute)attrs[0];
                    dic.Add(p.Name, new KeyValuePair<string, int>(attr.Name, attr.Ordinal));
                }
            }
            return dic;
        }


        /// <summary>
        /// 获取导出的列排序值(按原值（如101，203，100，...）从0开始重新设置连续的新值(如：0，1，2，...)
        /// </summary>
        /// <param name="type">实体类型</param>
        /// <param name="excepts">要排除的项</param>
        /// <returns></returns>
        public static Dictionary<string, int> GetImportOrdinal(Type type, List<string> excepts, Dictionary<string, string> dicMapping)
        {
            //取出需要导出的属性及排序值
            Dictionary<string, KeyValuePair<string, int>> dicKVP = ReflectionHelper.GetImportOrdinal(type, false);

            Dictionary<string, int> dicResult = new Dictionary<string, int>();
            foreach (var pName in dicKVP.Keys)
            {
                if (excepts != null && excepts.Contains(pName))
                    continue;

                string columnName = dicKVP[pName].Key;
                int ordinal = dicKVP[pName].Value;

                if (dicMapping != null && dicMapping.Keys.Contains(pName))
                    columnName = dicMapping[pName];
                if (!dicResult.Keys.Contains(columnName))
                    dicResult.Add(columnName, ordinal);
            }

            //升序排序
            Dictionary<string, KeyValuePair<string, int>> dicOrdered = dicResult.OrderBy(o => o.Value).ToDictionary(p => p.Key);

            dicResult.Clear();

            int i = 0;
            int len = dicOrdered.Count - 1;

            //根据排序好的集合索引号，重新生成排序编号
            foreach (var cName in dicOrdered.Keys)
            {
                int ordinal = dicOrdered[cName].Value;
                if (ordinal > 0)
                    dicResult.Add(cName, i++);
                else
                    dicResult.Add(cName, len--);
            }

            return dicResult;
        }

        /// <summary>
        /// 获取类型T的DisplayName
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetDisplayName<T>()
        {
            return GetDisplayName(typeof(T), typeof(T).Name);
        }

        /// <summary>
        /// 获取类型type的DisplayName
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetDisplayName(Type type)
        {
            return GetDisplayName(type, type.Name);
        }

        /// <summary>
        /// 获取类型T中所有属性的DisplayNames集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Dictionary<string, string> GetDisplayNames<T>()
        {
            return GetDisplayNames(typeof(T));
        }

        /// <summary>
        /// 获取类型type中所有属性的DisplayNames集合
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetDisplayNames(Type type)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo p in properties)
            {
                string displayName = GetDisplayName(p, string.Empty);

                if (!String.IsNullOrEmpty(displayName))
                {
                    dic.Add(p.Name, displayName);
                }


            }
            return dic;
        }



        /// <summary>
        /// 对象转换（匹配属性名称)
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TTarget">目标类型</typeparam>
        /// <param name="source">源对象</param>
        /// <param name="target">目标对象</param>
        public static void Copy<TSource, TTarget>(TSource source, TTarget target)
        {
            PropertyInfo[] properties = typeof(TSource).GetProperties();

            foreach (PropertyInfo p in properties)
            {
                if (p.CanWrite)
                {
                    PropertyInfo dbProperty = typeof(TTarget).GetProperty(p.Name);
                    if (dbProperty != null)
                    {
                        dbProperty.SetValue(target, p.GetValue(source, null), null);
                    }
                }
            }
        }

        public static void SetPropertyValue(object model, string pName, object value)
        {

            if (model == null || String.IsNullOrEmpty(pName))
                return;

            string[] pNames = pName.Split('.');
            int length = pNames.Length;


            if (length > 1) //为自定义类型属性赋值， 形如：model.Customer.Name 、model.Customer.Bank.Code
            {

                object p = model;
                object pLast = p;
                string pNameLast = pName.Split('.')[length - 1];

                for (int i = 0; i < length - 1; i++)
                {
                    string pNameTemp = pNames[i];

                    if (pNameTemp.Contains("[0]"))//集合类型属性
                    {
                        p = pLast = GetPropertyValue(pLast, pNameTemp.Split('[')[0]);
                    }
                    else
                    {
                        p = TryGetPropertyValue(p, pNameTemp);
                        SetPropertyValue(pLast, pNameTemp, p);
                        pLast = p;
                    }
                }
                SetPropertyValue(pLast, pNameLast, value);
            }
            else
            {
                PropertyInfo property = model.GetType().GetProperty(pName);

                if (property != null)//为系统类型属性赋值形如：model.Name
                {
                    Type pType = property.PropertyType;

                    if (pType.BaseType == typeof(System.Enum))
                    {
                        property.SetValue(model, EnumHelper.GetEnum(pType, value.ToString(), null), null);
                    }
                    else if (pType.Module.Name.Contains("mscorlib"))
                    {
                        try
                        {
                            if (pType.IsGenericType && !typeof(ICollection).IsAssignableFrom(pType))
                                pType = Nullable.GetUnderlyingType(pType);
                            if (pType.IsSubclassOf(typeof(System.ValueType)) && String.IsNullOrEmpty(value.ToString()))
                            {
                                if (pType == typeof(decimal) || pType == typeof(int) || pType == typeof(double))
                                    value = 0;//解决清空输入框，保存后值未清零的问题2015.11.1
                                else
                                    return; //DateTime,Bool
                            }
                            if (pType == typeof(String) && value != null)
                                value = value.ToString().Trim();
                            property.SetValue(model, Convert.ChangeType(value, pType), null);
                        }
                        catch (ArgumentException ex)
                        {

                            string displayName = ReflectionHelper.GetDisplayName(property, pName);
                            //throw new ArgumentException(string.Format("属性{0}只读！", displayName));
                            //TextHelper.AppendString("./RelectionHelper.log", string.Format("[{0}]属性{1}只读！", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), displayName));

                        }
                        catch (InvalidCastException ex)
                        {
                            string displayName = ReflectionHelper.GetDisplayName(property, pName);
                            throw new InvalidCastException(string.Format("“{0}”项“{1}”值格式不正确，应为：{2}！", displayName, value, pType.Name));
                        }
                        catch (FormatException ex)
                        {

                            if (pType == typeof(DateTime))
                                throw new FormatException("填写值：" + value + " 不是正确日期，参照：2015-01-01 ");
                            else if (pType == typeof(Decimal))
                                throw new FormatException("填写值：" + value + " 不是正确金额，参照：100.00 ");
                            else
                            {
                                string path = WebHelper.CurContext.Server.MapPath("~/reflectionHelper.error");
                                TextHelper.AppendString(path, string.Format("========{0}\t项:{1}  类型:{2}  输入值:{3}  格式有误:{4}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), property.Name, pType.Name, value, ex.Message));
                                return;
                                //throw new FormatException(string.Format("项： {0}  类型： {1}  输入值： {2}  格式有误： {3}", property.Name, pType.Name, value, ex.Message));
                            }
                        }
                    }
                }
                else if (model is IList && model.GetType().IsGenericType)
                {
                    IList list = model as IList;
                    Type genericType = model.GetType().GetGenericArguments()[0];

                    object item = null;

                    if (list.Count > 0 && list[0] != null)
                    {
                        item = list[0];
                    }
                    else
                    {
                        item = Activator.CreateInstance(genericType);
                        list.Add(item);
                    }
                    SetPropertyValue(item, pName, value);
                }
            }
        }

        /// <summary>
        /// 为实体对象属性赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="properties_values"></param>
        public static void SetPropertyValue<T>(T model, Dictionary<string, object> properties_values)
        {
            foreach (var key in properties_values.Keys)
            {
                SetPropertyValue(model, key, properties_values[key]);
            }
        }

        /// <summary>
        /// 为实体对象属性赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="properties_values"></param>
        public static void SetPropertyValue<T>(T model, Dictionary<string, string> properties_values)
        {
            foreach (var key in properties_values.Keys)
            {
                SetPropertyValue(model, key, properties_values[key]);
            }
        }

        /// <summary>
        /// 获取特性标签值
        /// </summary>
        /// <typeparam name="T">目标实体类型</typeparam>
        /// <typeparam name="TAttribute">特性类型</typeparam>
        /// <param name="attributeProperyName">特性属性名称</param>
        /// <returns></returns>
        public static string GetAttributeValue<TAttribute>(MemberInfo info, string attributeProperyName)
        {
            string attrValue = string.Empty;

            object[] attrs = info.GetCustomAttributes(typeof(TAttribute), true);
            if (attrs != null && attrs.Length > 0)
            {
                object value = GetPropertyValue<TAttribute>((TAttribute)attrs[0], attributeProperyName);
                if (value != null)
                {
                    attrValue = value.ToString();
                }
            }
            return attrValue;
        }
        /// <summary>
        /// 判断属性是否有特性标签TAttribute
        /// </summary>
        /// <typeparam name="TAttribute">特性标签类型</typeparam>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool HasAttribute<TAttribute>(MemberInfo info)
        {
            object[] attrs = info.GetCustomAttributes(typeof(TAttribute), true);
            return attrs != null && attrs.Length > 0;
        }

        /// <summary>
        /// 判断属性是否有特性标签TAttribute
        /// </summary>
        /// <typeparam name="TAttribute">特性标签类型</typeparam>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool HasAttribute<T, TAttribute>(string propertyName)
        {
            PropertyInfo info = typeof(T).GetProperty(propertyName);
            if (info == null)
                return false;

            object[] attrs = info.GetCustomAttributes(typeof(TAttribute), true);
            return attrs != null && attrs.Length > 0;
        }

        /// <summary>
        ///  判断属性是否有特性标签TAttribute
        /// </summary>
        /// <param name="ojbType"></param>
        /// <param name="attributeType">特性标签</param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static bool HasAttribute(object obj, Type attributeType, string propertyName)
        {
            PropertyInfo info = obj.GetType().GetProperty(propertyName);
            if (info == null)
                return false;

            object[] attrs = info.GetCustomAttributes(attributeType, true);
            // propertyName = ReflectionHelper.GetAttributeValue<JsonSerializeAttribute>(pi, attributeName);
            return attrs != null && attrs.Length > 0;
        }

        /// <summary>
        /// 获取类型T上的导入导出特性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetImportField<T>()
        {
            string value = string.Empty;

            if (HasAttribute<ImportFieldAttribute>(typeof(T)))
            {
                value = GetAttributeValue<ImportFieldAttribute>(typeof(T), "Name");
                if (String.IsNullOrEmpty(value))
                {
                    value = GetDisplayName<T>();
                }
            }
            return value;
        }

        /// <summary>
        /// 获取属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="pName"></param>
        /// <returns></returns>
        public static object GetPropertyValue<T>(T model, string pName)
        {
            if (model == null || String.IsNullOrEmpty(pName))
                return null;

            object value = null;
            string[] pNames = pName.Split('.');
            int length = pNames.Length;

            //取系统类型属性值，形如：model.Name
            if (length == 1)
            {
                PropertyInfo property = model.GetType().GetProperty(pName);
                if (property != null)
                {
                    try
                    {
                        //取BillURL("//UploadFiles//" + this.Organization.ID + "//Bill//" + this.ID + ".png" )这类属性会报错
                        value = property.GetValue(model, null);
                    }
                    catch (Exception ex)
                    {
                        string path = WebHelper.CurContext.Server.MapPath("~/reflectionHelper.error");
                        TextHelper.AppendString(path, string.Format("========{0} 方法名：GetPropertyValue 类名：{1}  属性名：{2}  对象:{3}  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), typeof(T), property.Name, model));
                        return null;
                    }
                }
            } //取自定义类型属性值，形如：model.Customer.Name 、model.Customer.Bank.Code
            else
            {
                object p = model;
                object pLast = p;
                string pNameLast = pName.Split('.')[length - 1];

                for (int i = 0; i < length - 1; i++)
                {
                    string pNameTemp = pNames[i];
                    //不导出集合类型属性，形如：model.Details，如需要，请单独导出
                    if (!pNameTemp.Contains("[0]"))
                    {
                        p = GetPropertyValue(p, pNameTemp);
                        pLast = p;
                    }
                }
                value = GetPropertyValue(pLast, pNameLast);
            }
            return value;
        }

        /// <summary>
        /// 获取类的属性名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IList<string> GetProperties<T>()
        {

            PropertyInfo[] properties = typeof(T).GetProperties();
            List<string> pNames = new List<string>();
            foreach (var p in properties)
            {
                pNames.Add(p.Name);
            }
            return pNames;
        }

        static object TryGetPropertyValue(object model, string propertyName)
        {
            PropertyInfo property = null;
            object pValue = null;
            if (model is IList && model.GetType().IsGenericType)
            {
                IList list = model as IList;
                if (list.Count > 0)
                {
                    property = list[0].GetType().GetProperty(propertyName);
                    pValue = GetPropertyValue(list[0], propertyName);
                }
            }
            else
            {
                property = model.GetType().GetProperty(propertyName);
                pValue = GetPropertyValue(model, propertyName);
            }

            if (pValue == null)
            {
                pValue = Activator.CreateInstance(property.PropertyType);
            }
            return pValue;
        }

        public static bool TryChangeType<T>(string propertyName, ref object value)
        {
            bool isSucceed = true;
            try
            {
                Type propertyType = GetPropertyType<T>(propertyName);

                if (propertyType == null)
                    isSucceed = false;
                else
                    value = Convert.ChangeType(value, propertyType);
            }
            catch
            {

                isSucceed = false;
            }
            return isSucceed;
        }

        public static Type GetPropertyType<T>(string propertyName)
        {
            PropertyInfo pi = typeof(T).GetProperty(propertyName);
            if (pi != null)
                return pi.PropertyType;
            else
                return null;
        }

        public static bool HasProperty<T>(string propertyName)
        {
            return typeof(T).GetProperty(propertyName) != null;
        }

    }

    #region
    //public class ReflectionHelper
    //{
    //    
    //    public static Type[] FindInterfaces(Type t, string interfaceName)
    //    {
    //        TypeFilter filter = new TypeFilter(ReflectionHelper.InterfaceFilter);
    //        return t.FindInterfaces(filter, interfaceName);
    //    }

    //    public static string GetDescription(MemberInfo memberInfo)
    //    {
    //        return GetDescription(memberInfo, null);
    //    }

    //    private static string GetDescription(string name)
    //    {
    //        switch (name.ToLower())
    //        {
    //            case "guid":
    //                return "全局标识";

    //            case "id":
    //                return "标识";

    //            case "serialno":
    //                return "序列";

    //            case "name":
    //                return "名称";

    //            case "code":
    //                return "代码";

    //            case "category":
    //                return "分类";

    //            case "comment":
    //                return "注释";

    //            case "description":
    //                return "说明";

    //            case "remark":
    //                return "备注";

    //            case "tag":
    //                return "标签";

    //            case "stop":
    //                return "停用";

    //            case "count":
    //                return "计数";

    //            case "item":
    //                return "项目";

    //            case "identity":
    //                return "识别要素";

    //            case "value":
    //            case "values":
    //                return "值";

    //            case "key":
    //            case "keys":
    //                return "键";
    //        }
    //        return StringHelper.Amead(name, ' ');
    //    }

    //    public static string GetDescription(MemberInfo memberInfo, string defaultDesc)
    //    {
    //        if (memberInfo != null)
    //        {
    //            object[] customAttributes = memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
    //            if ((customAttributes != null) && (customAttributes.Length > 0))
    //            {
    //                return ((DescriptionAttribute)customAttributes[0]).Description;
    //            }
    //            if (defaultDesc != null)
    //            {
    //                return defaultDesc;
    //            }
    //            return GetDescription(memberInfo.Name);
    //        }
    //        return null;
    //    }

    //    public static string GetDisplayName(MemberInfo memberInfo)
    //    {
    //        return GetDisplayName(memberInfo, null);
    //    }

    //    public static string GetDisplayName(MemberInfo memberInfo, string defaultDisplayName)
    //    {
    //        if (memberInfo != null)
    //        {
    //            object[] customAttributes = memberInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true);
    //            if ((customAttributes != null) && (customAttributes.Length > 0))
    //            {
    //                return ((DisplayNameAttribute)customAttributes[0]).DisplayName;
    //            }
    //            if (defaultDisplayName != null)
    //            {
    //                return defaultDisplayName;
    //            }
    //            return GetDescription(memberInfo.Name);
    //        }
    //        return null;
    //    }

    //    public static string GetFieldDescription<T>(string fieldName)
    //    {
    //        return GetFieldDescription<T>(fieldName, null);
    //    }

    //    public static string GetFieldDescription<T>(string fieldName, string defaultDesc)
    //    {
    //        return GetFieldDescription(typeof(T), fieldName, defaultDesc);
    //    }

    //    public static string GetFieldDescription(Type type, string fieldName)
    //    {
    //        return GetFieldDescription(type, fieldName, null);
    //    }

    //    public static string GetFieldDescription(Type type, string fieldName, string defaultDesc)
    //    {
    //        if (!string.IsNullOrEmpty(fieldName))
    //        {
    //            return GetDescription(type.GetField(fieldName), defaultDesc);
    //        }
    //        return null;
    //    }

    //    public static object GetPrivateField(object objectHandle, string fieldName)
    //    {
    //        FieldInfo field = objectHandle.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    //        if (field != null)
    //        {
    //            return field.GetValue(objectHandle);
    //        }
    //        return null;
    //    }

    //    public static object GetPrivateProperty(object objectHandle, string propertyName)
    //    {
    //        BindingFlags flags = BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance;
    //        string methodName = "get_" + propertyName;
    //        return InvokeMethod(objectHandle, methodName, null, flags);
    //    }

    //    public static string GetPropertyDescription<T>(string propertyName)
    //    {
    //        return GetPropertyDescription<T>(propertyName, null);
    //    }

    //    public static string GetPropertyDescription<T>(string propertyName, string defaultDesc)
    //    {
    //        return GetPropertyDescription(typeof(T), propertyName, defaultDesc);
    //    }

    //    public static string GetPropertyDescription(Type type, string propertyName)
    //    {
    //        return GetPropertyDescription(type, propertyName, null);
    //    }

    //    public static string GetPropertyDescription(Type type, string propertyName, string defaultDesc)
    //    {
    //        if (!string.IsNullOrEmpty(propertyName))
    //        {
    //            return GetDescription(type.GetProperty(propertyName), defaultDesc);
    //        }
    //        return null;
    //    }

    //    public static string GetPropertyDisplayName<T>(string propertyName)
    //    {
    //        return GetPropertyDisplayName<T>(propertyName, null);
    //    }

    //    public static string GetPropertyDisplayName<T>(string propertyName, string defaultDisplayName)
    //    {
    //        return GetPropertyDisplayName(typeof(T), propertyName, defaultDisplayName);
    //    }

    //    public static string GetPropertyDisplayName(Type type, string propertyName)
    //    {
    //        return GetPropertyDisplayName(type, propertyName, null);
    //    }

    //    public static string GetPropertyDisplayName(Type type, string propertyName, string defaultDisplayName)
    //    {
    //        if (!string.IsNullOrEmpty(propertyName))
    //        {
    //            PropertyInfo property;
    //            try
    //            {
    //                property = type.GetProperty(propertyName);
    //            }
    //            catch (AmbiguousMatchException)
    //            {
    //                property = type.GetProperty(propertyName, BindingFlags.DeclaredOnly);
    //            }
    //            return GetDisplayName(property, defaultDisplayName);
    //        }
    //        return null;
    //    }

    //    public static object GetPublicProperty(object objectHandle, string propertyName)
    //    {
    //        BindingFlags flags = BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance;
    //        string methodName = "get_" + propertyName;
    //        return InvokeMethod(objectHandle, methodName, null, flags);
    //    }

    //    private static bool InterfaceFilter(Type typeObj, object criteriaObj)
    //    {
    //        return (((typeObj != null) && (criteriaObj != null)) && (typeObj.ToString() == criteriaObj.ToString()));
    //    }

    //    private static object InvokeMethod(object objectHandle, string methodName, object[] paras, BindingFlags flags)
    //    {
    //        MethodInfo method;
    //        Type type = objectHandle.GetType();
    //        try
    //        {
    //            method = type.GetMethod(methodName, flags);
    //        }
    //        catch (AmbiguousMatchException)
    //        {
    //            method = type.GetMethod(methodName, flags | BindingFlags.DeclaredOnly);
    //        }
    //        if (method == null)
    //        {
    //            throw new MissingMethodException(type.ToString(), methodName);
    //        }
    //        ParameterInfo[] parameters = method.GetParameters();
    //        if ((parameters == null) || (parameters.Length == 0))
    //        {
    //            return method.Invoke(objectHandle, null);
    //        }
    //        return method.Invoke(objectHandle, paras);
    //    }

    //    public static object InvokePrivateMethod(object objectHandle, string methodName, object[] paras)
    //    {
    //        BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance;
    //        return InvokeMethod(objectHandle, methodName, paras, flags);
    //    }

    //    public static object InvokePublicMethod(object objectHandle, string methodName, object[] paras)
    //    {
    //        BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance;
    //        return InvokeMethod(objectHandle, methodName, paras, flags);
    //    }

    //    public static void SetPrivateField(object objectHandle, string fieldName, object value)
    //    {
    //        FieldInfo field = objectHandle.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    //        if (field != null)
    //        {
    //            field.SetValue(objectHandle, value);
    //        }
    //    }

    //    public static void SetPrivateProperty(object objectHandle, string propertyName, object value)
    //    {
    //        BindingFlags flags = BindingFlags.SetProperty | BindingFlags.NonPublic | BindingFlags.Instance;
    //        string methodName = "set_" + propertyName;
    //        InvokeMethod(objectHandle, methodName, new object[] { value }, flags);
    //    }

    //    public static void SetPublicProperty(object objectHandle, string propertyName, object value)
    //    {
    //        BindingFlags flags = BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance;
    //        string methodName = "set_" + propertyName;
    //        InvokeMethod(objectHandle, methodName, new object[] { value }, flags);
    //    }
    //}
    #endregion
}

